package com.ddm.withoutpaper;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;

import com.ddm.withoutpaper.controller.UIController;



public class LoginActivity extends Activity implements OnClickListener {
	
	private EditText login;
	private EditText senha;
	private Button buttonEntrar;
	private ProgressBar loading;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		
		this.login = (EditText) findViewById(R.id.login);
		this.senha = (EditText) findViewById(R.id.senha);
		this.buttonEntrar = (Button) findViewById(R.id.buttonEntrar);
		
		if (UIController.getInstance().verificaLogin(LoginActivity.this)) {
			UIController.getInstance().setScreen(LoginActivity.this, MenuActivity.class);
		}
		
		this.buttonEntrar.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		
		loading = (ProgressBar)findViewById(R.id.progressBar);
		loading.setVisibility(0);
		
		if (v.equals(buttonEntrar)) {
			LoginAsyncTask async = new LoginAsyncTask();
			async.execute(login.getText().toString(), senha.getText().toString());
		}
	}
	
	private class LoginAsyncTask extends AsyncTask<String, Void, Boolean> {

		private String user = null;
		private String password = null;

		@Override
		protected Boolean doInBackground(String... params) {
			user = params[0];
			password = params[1];
			
			return UIController.getInstance().login(user, password);
		}

		@Override
		protected void onPostExecute(Boolean logged) {
			if (logged) {
				UIController.getInstance().setScreen(LoginActivity.this, MenuActivity.class);
				UIController.getInstance().registraLogin(LoginActivity.this, user);
			} else {
				new AlertDialog.Builder(LoginActivity.this)
						.setIcon(android.R.drawable.ic_dialog_alert)
						.setTitle("Aviso!").setMessage("Falha de login.")
						.show();
				loading.setVisibility(4);
			}
		}
	}
}
